<?php

namespace app\thumber\controller;

use \think\Controller;
use think\Request;
use EvaThumber\Thumber;
use think\Exception;
class Index extends Controller {
    
    public function index() {
//        echo url('thumber/index/index', ['config' => 'd', 'path' => base64_encode("demo"), 'query' => 'c_100,r_50'], 'png');die;
//        dump(config('thumbers'));die;
        $url = $this->genUrl();
//        echo $url;die;
        $config = config('thumbers');
        try {
            $thumber = new Thumber($config, $url);
            $thumber->show();
            exit();
        } catch (Exception $e) {
//            throw $e;
            return redirect($config['thumbers']['d']['error_url'] . '?msg=' . urlencode($e->getMessage()));
        }
    }

    private function genUrl() {
        $request = Request::instance();
        $param = $request->param();
        $url = '/thumb';
        if (isset($param['config'])) {
            $url .= "/" .trim($param['config']);
        }else{
            $url .= '/d';
        }
        if (isset($param['path'])) {
            $url .= "/" . base64_decode(($param['path']));
        }
        if (isset($param['query'])) {
            $query = array_filter(explode(",", $param['query']));
            if (!empty($query)) {
                asort($query);
                $url .= "," . implode(",", $query);
            }
        }
        
        if (!empty($request->ext())) {
            $url .= "." . trim($request->ext());
        }else{
            $url .= ".png";
        }
        return $request->domain() . $url;
    }
}
